package ctn.web.home.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jmesa.core.filter.DateFilterMatcher;
import org.jmesa.core.filter.MatcherKey;
import org.jmesa.limit.ExportType;
import org.jmesa.limit.Limit;
import org.jmesa.model.PageItems;
import org.jmesa.model.TableModel;
import org.jmesa.model.TableModelUtils;
import org.jmesa.view.component.Table;
import org.jmesa.view.editor.CellEditor;
import org.jmesa.view.editor.DateCellEditor;
import org.jmesa.view.html.HtmlBuilder;
import org.jmesa.view.html.component.HtmlColumn;
import org.jmesa.view.html.component.HtmlTable;
import org.jmesa.view.html.event.RowEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

import ctn.contant.PlugContant;
import ctn.contant.WebConstant;
import ctn.hibernate.po.CtnCpaSpec;
import ctn.hibernate.po.CtnUser;
import ctn.service.dto.PlugDTO;
import ctn.service.dto.PlugFileDTO;
import ctn.service.dto.SpecDTO;
import ctn.service.inteface.PlugService;
import ctn.service.inteface.SpecService;
import ctn.service.inteface.UserService;
import ctn.util.CPAUtil;
import ctn.util.CTNUserUtil;
import ctn.util.StringUtils;
import ctn.util.jmesa.DateUtils;
import ctn.util.jmesa.PageFilter;
import ctn.util.jmesa.PageSorter;
import ctn.util.jmesa.PaginationCriteria;
import ctn.util.jmesa.TableFacadeUtils;

@Controller
public class PlugController {
	@Autowired
	@Qualifier("filePro")
	private Properties filePro;

	@Autowired
	private PlugService plugServiceImpl;

	@Autowired
	private SpecService specServiceImpl;
	
	@Autowired
	private CPAUtil cpaUtil;
	@Autowired
	private UserService userService;
	
	@RequestMapping(value = "/main/wplug")
	public ModelAndView wplug(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ModelAndView mv = new ModelAndView("plug/plugShow");
		final String statusParm=request.getParameter("status");
		TableModel tableModel = new TableModel("wplug", request, response);
		tableModel.setStateAttr("restore");
		tableModel.setExportTypes(new ExportType[] { ExportType.EXCEL });
		final PaginationCriteria criteria = new PaginationCriteria();
		tableModel.addFilterMatcher(new MatcherKey(Date.class, "createDate"), new DateFilterMatcher("yyyy-MM-dd"));
		tableModel.addFilterMatcher(new MatcherKey(Date.class, "CompleteDate"), new DateFilterMatcher("yyyy-MM-dd"));
		tableModel.setItems(new PageItems() {

			@Override
			public int getTotalRows(Limit limit) {
				PageFilter pageFilter = TableFacadeUtils.getPageFilter(limit,
						PlugDTO.class);
				if(!StringUtils.isEmptyString(statusParm)){
					pageFilter.addFilter("status", statusParm);
				}
				criteria.setPageFilter(pageFilter);

				return plugServiceImpl.getWplugListCount(criteria).intValue();
			}

			@Override
			public List<PlugDTO> getItems(Limit limit) {
				PageSorter pageSorter = TableFacadeUtils.getPageSorter(limit);
				int rowStart = limit.getRowSelect().getRowStart();
				int rowEnd = limit.getRowSelect().getRowEnd();
				criteria.setPageSorter(pageSorter);
				criteria.setRowStart(rowStart);
				criteria.setRowEnd(rowEnd);
				return plugServiceImpl.getWplugList(criteria);
			}
		});
		 if (tableModel.isExporting()) {
	            tableModel.setTable(getExportTable(statusParm));
	        } else {
	            tableModel.setTable(getHtmlTable(statusParm));
	        }
		   String view = tableModel.render();
	        if (view == null) {
	            return null; // an export
	        } else {
	            // Setting a parameter to signal that this is an Ajax request.
	            String ajax = request.getParameter("ajax");
	            if (ajax != null && ajax.equals("true")) {
	                byte[] contents = view.getBytes();
	                response.getOutputStream().write(contents);
	                return null;
	            } else { // Not using Ajax if invoke the controller for the first time.
	                mv.addObject("wplughtml", view); // Set the Html in the request for the JSP.
	                mv.addObject("status",statusParm);
	            }
	        }

	        return mv;
	}
	private Table getExportTable(String status) {
        Table table = TableModelUtils.createTable("ID","cpaName","createUserName","createDate","version","CompleteDate");
        if(StringUtils.isEmptyString(status)||PlugContant.STATUS_WAIT.equals(status)){
        	table.setCaption("待开发的插件");
        }else if(PlugContant.STATUS_DOING.equals(status)){
        	table.setCaption("正开发的插件");
        }else if(PlugContant.STATUS_END.equals(status)){
        	table.setCaption("已完成的插件");
        }else if(PlugContant.STATUS_CLOSE.equals(status)){
        	table.setCaption("已关闭的插件");
        }

        table.getRow().getColumn("ID").setTitle("编号");
        table.getRow().getColumn("cpaName").setTitle("插件名称");
        table.getRow().getColumn("createUserName").setTitle("创建人");
        table.getRow().getColumn("createDate").setTitle("创建日期");
        table.getRow().getColumn("version").setTitle("当前版本");
        table.getRow().getColumn("CompleteDate").setTitle("当前版本完成日期");
        return table;
    }

    private Table getHtmlTable(String status) {
        HtmlTable htmlTable  = TableModelUtils.createHtmlTable("ID","cpaName","createUserName","createDate","version","CompleteDate","action");
        if(StringUtils.isEmptyString(status)||PlugContant.STATUS_WAIT.equals(status)){
        	htmlTable.setCaption("待开发的插件");
        }else if(PlugContant.STATUS_DOING.equals(status)){
        	htmlTable.setCaption("正开发的插件");
        }else if(PlugContant.STATUS_END.equals(status)){
        	htmlTable.setCaption("已完成的插件");
        }else if(PlugContant.STATUS_CLOSE.equals(status)){
        	htmlTable.setCaption("已关闭的插件");
        }
        htmlTable.getRow().setOnmouseover(new RowEvent(){

			@Override
			public String execute(Object item, int rowcount) {
				return "showDescInfo("+((PlugDTO)item).getID()+")";
			}
        	
        });
        htmlTable.setStyle("width:90%;");
        htmlTable.getRow().getColumn("ID").setTitle("编号");
        htmlTable.getRow().getColumn("ID").setWidth("5%");
        htmlTable.getRow().getColumn("cpaName").setTitle("插件名称");
        htmlTable.getRow().getColumn("cpaName").setWidth("25%");
        htmlTable.getRow().getColumn("createUserName").setTitle("创建人");
        htmlTable.getRow().getColumn("createUserName").setWidth("10%");
        htmlTable.getRow().getColumn("createDate").setTitle("创建日期");
        htmlTable.getRow().getColumn("createDate").setWidth("15%");
        htmlTable.getRow().getColumn("createDate").setCellEditor(new DateCellEditor("yyyy-MM-dd"));
        htmlTable.getRow().getColumn("version").setTitle("当前版本");
        htmlTable.getRow().getColumn("version").setWidth("15%");
        htmlTable.getRow().getColumn("CompleteDate").setTitle("当前版本完成日期");
        htmlTable.getRow().getColumn("CompleteDate").setWidth("15%");
        htmlTable.getRow().getColumn("CompleteDate").setCellEditor(new DateCellEditor("yyyy-MM-dd"));
        htmlTable.getRow().getColumn("CompleteDate").setSortable(false);
        htmlTable.getRow().getColumn("version").setSortable(false);
        HtmlColumn action=htmlTable.getRow().getColumn("action");
        action.setTitle("操作");
        action.setWidth("15%");
        action.setCellEditor(new CellEditor() {
			
			@Override
			public Object getValue(Object item, String property, int rowcount) {
				PlugDTO dto=(PlugDTO)item;
				CtnCpaSpec spec=specServiceImpl.getSpecByCapVerFun(dto.getVerID(),null);
				HtmlBuilder html = new HtmlBuilder(); 
				//if(!StringUtils.isEmptyString(dto.getCreateUserName())&&dto.getCreateUserName().equals(CTNUserUtil.getUser().getName())){
					html.ahref("./previewPlug?id="+dto.getID(), "查看").aEnd();
					//html.a().href("#1").onclick("delPlug("+((PlugDTO)item).getID()+")").close().append("删除").aEnd();
					
					//待开发准状态
					if(PlugContant.STATUS_WAIT.equalsIgnoreCase(dto.getVerStatus())){
						if(CTNUserUtil.getUser().getName().equalsIgnoreCase(dto.getCreateUserName())){
							html.nbsp();
							html.ahref("./preeditplug?id="+dto.getID(), "编辑").aEnd();
						}
						html.nbsp();
						///main/downspec?id
//						html.ahref("./plugfilelist?path="+dto.getID(), "下载文档").aEnd();
						
						
						html.ahref("./downspec?id="+spec.getId(), "下载文档").aEnd();
						//html.a().href("#1").onclick("editPlug("+((PlugDTO)item).getID()+")").close().append("编辑").aEnd();
						
					}
					
					//正在开发状态
					if(PlugContant.FUN_STATUS_DOING.equalsIgnoreCase(dto.getVerStatus())){
						if(CTNUserUtil.getUser().getName().equalsIgnoreCase(dto.getCreateUserName())){
							html.nbsp();
							html.ahref("./preeditplug?id="+dto.getID(), "编辑").aEnd();
						}
						html.nbsp();
						html.ahref("./predelPlug?id="+dto.getID(), "删除").aEnd();
						html.nbsp();
						html.ahref("./preViewTeam?id="+dto.getID(), "查看详细").aEnd();
						Long userId= CTNUserUtil.getUser().getId();
						//if(CTNUserUtil.getUser().getName().equalsIgnoreCase(dto.getCreateUserName())){
							html.nbsp();
							html.ahref("./viewfun?cpaid="+dto.getID()+"&verid="+dto.getVerID()+"&userid="+userId, "管理模块").aEnd();
						//}
						
						
					}
					//已完成状态
					if(PlugContant.FUN_STATUS_COMPLETE.equalsIgnoreCase(dto.getVerStatus())){
						//if(CTNUserUtil.getUser().getName().equalsIgnoreCase(dto.getCreateUserName())){
							html.nbsp();
							html.ahref("./preeditplug?id="+dto.getID(), "编辑").aEnd();
						//}
						html.nbsp();
						html.ahref("./preViewTeam?id="+dto.getID(), "查看详细").aEnd();
						/*if(CTNUserUtil.getUser().getName().equalsIgnoreCase(dto.getCreateUserName())){
							html.nbsp();
							html.ahref("./premanagerPlug?id="+dto.getID(), "管理模块").aEnd();
						}*/
						
						
					}
					//html.a().href("#1").onclick("managerPlug("+((PlugDTO)item).getID()+")").close().append("管理模块").aEnd();
				//}
				/*List<CtnUser> users=plugServiceImpl.getDoPlugGrpUsers(((PlugDTO)item).getImplGrpID());
				for(CtnUser user:users){
					if(user.getId()==CTNUserUtil.getUser().getId()){
						html.a().href("#1").onclick("managerPlug("+((PlugDTO)item).getID()+")").close().append("管理模块").aEnd();
					}
				}*/
				return html.toString();
			}
		});
        return htmlTable;
    }
    @RequestMapping(value = "/main/preaddplug")
	public ModelAndView preAddPlug(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
    	ModelAndView mv=new ModelAndView("plug/addplug");
    	PlugDTO dto=new PlugDTO();
    	mv.addObject("plugDTO", dto);
    	return mv;
    }
    @RequestMapping(value = "/main/predelPlug")
   	public ModelAndView preDelPlug(HttpServletRequest request,
   			HttpServletResponse response) throws Exception {
    	Long id=new Long(request.getParameter("id"));
       	ModelAndView mv=new ModelAndView("index/successs");
       	PlugDTO delPlugDto=plugServiceImpl.getWplug(id);
//        sendEmail( delPlugDto);
        plugServiceImpl.delPlug(id);
        //plugServiceImpl.doTransCpaVer(delPlugDto.get);
       	PlugDTO dto=new PlugDTO();
       	mv.addObject("plugDTO", dto);
       	return mv;
       }
    
    @RequestMapping(value = "/main/previewPlug")
  	public ModelAndView preViewPlug(HttpServletRequest request,
  			HttpServletResponse response) throws Exception {
    	Long id=new Long(request.getParameter("id"));
      	ModelAndView mv=new ModelAndView("plug/editplug");
      	PlugDTO dto=plugServiceImpl.getWplug(id);
      	//PlugDTO dto=new PlugDTO();
      	mv.addObject("plugDTO", dto);
      	request.setAttribute("isEdit", "N");
      	return mv;
      }
    @RequestMapping(value = "/main/preeditplug")
  	public ModelAndView preEditPlug(HttpServletRequest request,
  			HttpServletResponse response) throws Exception {
    	//plug.file.path
    	String parentPath = filePro.getProperty("common.file.spec");
    	Long id=new Long(request.getParameter("id"));
    	
      	ModelAndView mv=new ModelAndView("plug/editplug");
      	PlugDTO dto=plugServiceImpl.getWplug(id);
      	//PlugDTO dto=new PlugDTO();
      	StringBuffer bf=new StringBuffer();
    	dto.setFilePath(parentPath);
      	mv.addObject("plugDTO", dto);

      	mv.addObject("path",
				URLEncoder.encode(parentPath, "utf-8"));
      	request.setAttribute("isEdit", "Y");
      	return mv;
      }
    /*
     * 待开发的插件中编辑操作
     */
    
    @RequestMapping(value = "/main/editplug")
	public ModelAndView editPlug(HttpServletRequest request,
			HttpServletResponse response,@ModelAttribute("plugDTO")PlugDTO plugDTO, BindingResult errors) throws Exception {
    	ModelAndView mv=new ModelAndView("index/success");
    	if(StringUtils.isEmptyString(plugDTO.getCpaName())){
    		errors.rejectValue("cpaName", null,  "插件名称不能为空。");
    	}
    	if(StringUtils.isEmptyString(plugDTO.getInfoDesc())){
    		errors.rejectValue("infoDesc", null,  "插件描述不能为空。");
    	}
    	if(!StringUtils.isEmptyString(plugDTO.getEffDateStr())){
    		Date effDate=DateUtils.parse("yyyy-MM-dd", plugDTO.getEffDateStr());
    		if(effDate.before(new Date())){
    			errors.rejectValue("effDateStr", null,  "生效日期不能早于今天");
    		}else{
    			plugDTO.setEffDate(effDate);
    		}
    	}
    	if(errors.hasErrors()){
    		if(plugDTO.getCreateUserName().equals(CTNUserUtil.getUser().getName())){
    			plugDTO.setEdit(true);
          	};
    		mv.setViewName("plug/editplug");
    	}else{
    		plugDTO.setCreateUserName(CTNUserUtil.getUser().getName());
    		plugDTO.setCreateDate(new Date());
    		if(PlugContant.STATUS_END.equalsIgnoreCase(plugDTO.getVerStatus())){
    			plugDTO.setCompleteDate(new Date());
    		}else{
    			plugDTO.setCompleteDate(null);
    		}
    		//plugDTO.setStatus(PlugContant.STATUS_WAIT);
    		if(plugDTO.getUpFile()!=null){
    			if(StringUtils.isEmptyString(plugDTO.getEffDateStr())){
    				plugDTO.setEffDate(new Date());
    			}
    		}
    		plugServiceImpl.editPlug(plugDTO);
    		
    		
      		
      		// sendEmail( plugDTO);
      	
    	}
    	
    	//request.getSession().setAttribute(WebConstant.USER, uv1);
    	return mv;
    }
    
    @RequestMapping(value = "/main/addplug")
  	public ModelAndView addPlug(HttpServletRequest request,
  			HttpServletResponse response,@ModelAttribute("plugDTO")PlugDTO plugDTO, BindingResult errors) throws Exception {
      	ModelAndView mv=new ModelAndView("index/success");
      	if(StringUtils.isEmptyString(plugDTO.getCpaName())){
      		errors.rejectValue("cpaName", null,  "插件名称不能为空。");
      	}
      	if(StringUtils.isEmptyString(plugDTO.getInfoDesc())){
      		errors.rejectValue("infoDesc", null,  "插件描述不能为空。");
      	}
      	if (plugDTO.getUpFile() == null) {
			errors.rejectValue("upFile", null, "文件路径不能为空。");
      	}
      	if(errors.hasErrors()){
      		mv.setViewName("plug/addplug");
      	}else{
      		CommonsMultipartFile uf = plugDTO.getUpFile();
      		plugDTO.setCreateUserName(CTNUserUtil.getUser().getName());
      		plugDTO.setCreateDate(new Date());
      		plugDTO.setVerStatus(PlugContant.STATUS_APPROVE);
      		plugServiceImpl.savePlug(plugDTO,uf);
      		
      	}
      	return mv;
      }
    @RequestMapping(value = "/link")
	public ModelAndView processLink(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
    	ModelAndView mv = new ModelAndView("index/success2");
    	String userID=request.getParameter(PlugContant.LINK_PARM_USER);
    	String UUID=request.getParameter(PlugContant.LINK_PARM_UUID);
    	if(StringUtils.isEmptyString(UUID)||StringUtils.isEmptyString(userID)){
    		mv.setViewName("index/error");
    		mv.addObject("msg","你的连接不正确");
    		return mv;
    	}
    	boolean linkEff=plugServiceImpl.processLink(UUID,userID);
    	if(!linkEff){
    		mv.setViewName("index/error");
    		mv.addObject("msg","你的连接不正确");
    		return mv;
    	}
    	boolean needLogin=plugServiceImpl.processEvent(UUID);
    	if(needLogin){
    		CtnUser user=userService.getCtnUserByID(userID);
    		request.getSession().setAttribute(WebConstant.USER, user);
    	}
    	return mv;
    	
    }
    
	@RequestMapping(value = "/main/prepluguploadf")
	public ModelAndView preuploadf(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ModelAndView mv = new ModelAndView("plug/uploadfile");
		PlugFileDTO dto = new PlugFileDTO();
		
		String id=request.getParameter("id");
		String verId=request.getParameter("verId");
		dto.setId(id);
		dto.setVerId(verId);
		dto.setFilePath(getFileAbsoultPath(request)+"/"+id+"/"+verId);
		mv.addObject("uploadFileDTO", dto);
		
		return mv;
	}
	private String getFileAbsoultPath(HttpServletRequest request)
			throws Exception {
		String parentPath = filePro.getProperty("common.file.spec");
		//String userName = CTNUserUtil.getUser().getName();
		StringBuffer path = new StringBuffer();
		path.append(parentPath);
		if(!StringUtils.isEmptyString(getChildPath(request))){
			path.append("\\");
			path.append(getChildPath(request));
		}
		return path.toString();
	}
	private String getChildPath(HttpServletRequest request) throws Exception {
		String childPath = request.getParameter("path");
		if (!StringUtils.isEmptyString(childPath)) {
			childPath = URLDecoder.decode(childPath, "utf-8");
		}
		return childPath == null ? "" : childPath;
	}
	@RequestMapping(value = "/main/pluguploadf")
	public ModelAndView uploadf(HttpServletRequest request,
			HttpServletResponse response,
			@ModelAttribute("uploadFileDTO") PlugFileDTO uploadFileDTO,
			BindingResult errors) throws Exception {
		
		ModelAndView mv = new ModelAndView("plug/uploadfile");

		if (uploadFileDTO.getUpFile() == null) {
			errors.rejectValue("upFile", null, "文件路径不能为空。");
		} else {
			
			CommonsMultipartFile uf = uploadFileDTO.getUpFile();
			File fileDir = new File(uploadFileDTO.getFilePath() +"/"+DateUtils.formatDateTime("yyyyMMdd", new Date()) );
			if(!fileDir.exists()){
				fileDir.mkdirs();
			}
			File file = new File(fileDir, uf.getOriginalFilename());
			//uploadFileDTO.getId();
			//uploadFileDTO.getVerId();
			SpecDTO specDTO=new SpecDTO();
			specDTO.setCreateDate(new Date());
			specDTO.setCreateUserName(CTNUserUtil.getUser().getName());
			specDTO.setSpecTyp("plug");
			//specServiceImpl.saveSpec(specDTO);
			BufferedOutputStream os = null;
			BufferedInputStream is = null;
			try {
				os = new BufferedOutputStream(new FileOutputStream(file));
				is = new BufferedInputStream(uf.getInputStream());

				byte[] byteA;
				int read = 0;
				while (read != -1) {
					byteA = new byte[1024];
					read = is.read(byteA);
					if (read != -1) {
						os.write(byteA, 0, read);
					}
				}
				os.flush();
			} finally {
				if (is != null) {
					is.close();
				}
				if (os != null) {
					try {
						os.close();
					} catch (Exception ex) {
					}
				}
			}
		}

		return mv;
	}
	
	
	/*@RequestMapping(value = "/main/plugfilelist")
	public ModelAndView fileList(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ModelAndView mv = new ModelAndView("plug/filelist");
		//String path=request.getParameter("path");
		File file = new File(getFileAbsoultPath(request));
		
		//String version=request.getParameter("version");
		if(!file.exists()){
			file.mkdirs();
		}
		//file.isDirectory()
		File[] fileArr = file.listFiles();
		List<PlugFileDTO> cfileList = new ArrayList<PlugFileDTO>();
		for (File cfile : fileArr) {
			PlugFileDTO pfile = new PlugFileDTO();
			pfile.setFileName(cfile.getName());
			String pfilepath = getChildPath(request) + "\\" +  URLEncoder.encode(cfile.getName(), "utf-8");
			//pfilepath = URLEncoder.encode(pfilepath, "utf-8");
			if (cfile.isDirectory()) {
				pfile.setFilePath(getFileAbsoultPath(request)+pfilepath);
				pfile.setFileUrl("/app/main/plugfilelist?path=" + pfilepath);
				pfile.setFileTyp("F");
			} else {
				pfile.setFileUrl("/app/main/plugopenFile?path=" + pfilepath);
				pfile.setFilePath(getFileAbsoultPath(request)+pfilepath);
				String fileExtStr = cfile.getName().substring(
						cfile.getName().lastIndexOf(".") + 1,
						cfile.getName().length());
				pfile.setFileTyp(fileExtStr);
			}

			cfileList.add(pfile);
		}
		mv.addObject("fileList", cfileList);
		mv.addObject("path",
				URLEncoder.encode(getFileAbsoultPath(request), "utf-8"));
		return mv;
	}
	
	@RequestMapping(value = "/main/plugopenFile")
	public void openFile(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String path = getFileAbsoultPath(request);
		File file = new File(path);
		response.setHeader("Pragma", "public");
		response.setHeader("Cache-Control", "max-age=0");
		response.setHeader("Content-Disposition", "attachment;filename="
				+ new String(file.getName().getBytes(), "UTF-8"));
		BufferedOutputStream os = null;
		BufferedInputStream is = null;
		try {
			os = new BufferedOutputStream(response.getOutputStream());
			is = new BufferedInputStream(new FileInputStream(file));

			byte[] byteA;
			int read = 0;
			while (read != -1) {
				byteA = new byte[1024];
				read = is.read(byteA);
				if (read != -1) {
					os.write(byteA, 0, read);
				}
			}
			os.flush();
		} finally {
			if (is != null) {
				is.close();
			}
			if (os != null) {
				try {
					os.close();
				} catch (Exception ex) {
				}
			}
		}

	}*/
}
